import * as echarts from 'echarts';
import 'echarts/extension/dataTool';
import { getCssVariableValue } from '@/utils/utils';

// 表头
const columnsMap = {
  // 24点位
  24: Array.from({ length: 24 }, (v, i) => {
    let hh = i + 1;
    hh = hh < 10 ? '0' + hh : hh;
    return {
      title: `${hh}00`,
      dataIndex: `${i}`,
      width: 55,
      align: 'center',
      render: (v) => (typeof v === 'string' && !!v ? v : '-'),
    };
  }),
  // 96点位
  96: Array.from({ length: 97 }, (v, i) => {
    let hh = Math.floor(i / 4);
    let mm = 15 * (i % 4) || '00';
    hh = hh < 10 ? '0' + hh : hh;
    return {
      title: `${hh}${mm}`,
      dataIndex: `${i - 1}`,
      width: 55,
      align: 'center',
      render: (v) => (typeof v === 'string' && !!v ? v : '-'),
    };
  }).slice(1),
};

// 箱体图配置
const chartOptionBase = () => {
  return {
    grid: { top: 48, left: 48, right: 0, bottom: 50 },
    tooltip: {
      formatter: (params) => {
        const result = {};

        params.forEach((item) => {
          if (item.seriesName === '日前价格分布' || item.seriesName === '实时价格分布') {
            const key =
              item.seriesName === '日前价格分布' ? 'beforeDistribution' : 'realTimeDistribution';
            result[key] = item.value;
          }
        });

        const datetime = params?.[0]?.name || '';
        const values1 = result.beforeDistribution;
        const values2 = result.realTimeDistribution;
        const space = '4px';
        return `<div style="color:#7A7D7F;margin-bottom:${space};">${datetime}</div>
                  <div style="display:flex;">
                    <div style="color:#D3D4D4;width:40px;">
                      <div style="margin-bottom:${space};">最低</div>
                      <div style="margin-bottom:${space};">Q1</div>
                      <div style="margin-bottom:${space};">中位</div>
                      <div style="margin-bottom:${space};">Q3</div>
                      <div>最高</div>
                    </div>
                    <div style="color:#7A7D7F;width:56px;">
                      <div style="margin-bottom:${space};">日前价格</div>
                      <div style="margin-bottom:${space};">日前价格</div>
                      <div style="margin-bottom:${space};">日前价格</div>
                      <div style="margin-bottom:${space};">日前价格</div>
                      <div>日前价格</div>
                    </div>
                    <div style="color:#5E92F6;text-align:right;">
                      <div style="margin-bottom:${space};">${
          _.isNil(values1?.[1]) ? '-' : values1?.[1]
        }</div>
                      <div style="margin-bottom:${space};">${
          _.isNil(values1?.[2]) ? '-' : values1?.[2]
        }</div>
                      <div style="margin-bottom:${space};">${
          _.isNil(values1?.[3]) ? '-' : values1?.[3]
        }</div>
                      <div style="margin-bottom:${space};">${
          _.isNil(values1?.[4]) ? '-' : values1?.[4]
        }</div>
                      <div>${_.isNil(values1?.[5]) ? '-' : values1?.[5]}</div>
                    </div>
                    <div style="color:#7A7D7F;width:56px;margin-left:16px;">
                      <div style="margin-bottom:${space};">实时价格</div>
                      <div style="margin-bottom:${space};">实时价格</div>
                      <div style="margin-bottom:${space};">实时价格</div>
                      <div style="margin-bottom:${space};">实时价格</div>
                      <div>实时价格</div>
                    </div>
                    <div style="color:#E86452;text-align:right;">
                      <div style="margin-bottom:${space};">${
          _.isNil(values2?.[1]) ? '-' : values2?.[1]
        }</div>
                      <div style="margin-bottom:${space};">${
          _.isNil(values2?.[2]) ? '-' : values2?.[2]
        }</div>
                      <div style="margin-bottom:${space};">${
          _.isNil(values2?.[3]) ? '-' : values2?.[3]
        }</div>
                      <div style="margin-bottom:${space};">${
          _.isNil(values2?.[4]) ? '-' : values2?.[4]
        }</div>
                      <div>${_.isNil(values2?.[5]) ? '-' : values2?.[5]}</div>
                    </div>
                  </div>`;
      },
    },
    legend: {
      textStyle: {
        color: getCssVariableValue('--chart-legend-color'),
      },
    },
    xAxis: [
      {
        type: 'category',
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisLine: {
          lineStyle: {
            type: 'solid',
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisTick: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
        axisPointer: {
          type: 'line',
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        name: '元/MWh',
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisTick: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
        splitLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
      },
    ],
  };
};

/**
 *
 * @param {object} dataSource 源数据
 * @param {string} pointKey 点位类型 24、96
 * @param {string} keySub 点位类型 修正前(UnadjustedPricesList)、修正后(PricesList)
 * @returns
 */
const fmtDataSource = (dataSource, pointKey, keySub, marketId) => {
  // 表头
  const timeList = columnsMap[pointKey];
  const tableColumns = [
    { dataIndex: 'typename', title: '类型', width: 110, fixed: 'left', align: 'center' },
    ...timeList,
  ];
  // 表格数据
  const tableData = [
    { typename: '日前价格-最低' },
    { typename: '日前价格-Q1' },
    { typename: '日前价格-中位' },
    { typename: '日前价格-Q3' },
    { typename: '日前价格-最高' },
    { typename: '实时价格-最低' },
    { typename: '实时价格-Q1' },
    { typename: '实时价格-中位' },
    { typename: '实时价格-Q3' },
    { typename: '实时价格-最高' },
  ];
  // 图表
  const chartSeries = [
    {
      type: 'boxplot',
      name: '日前价格分布',
      color: 'rgba(94, 146, 246, 0.2)',
      borderColor: '#5E92F6',
    },
    { type: 'line', name: '日前价格中位数', color: '#5E92F6' },
    {
      type: 'boxplot',
      name: '实时价格分布',
      color: 'rgba(232, 100, 82, 0.2)',
      borderColor: '#E86452',
    },
    { type: 'line', name: '实时价格中位数', color: '#E86452' },
  ];
  const chartOption = {
    ...chartOptionBase(),
  };
  // 数据处理
  if (marketId === 'PDBLJ' || marketId === 'PXBNX') {
    let aheadData = dataSource?.dayAheadlist || [];
    let realData = dataSource?.realtimelist || [];
    aheadData = echarts?.dataTool.prepareBoxplotData(aheadData).boxData; // 日前
    realData = echarts?.dataTool.prepareBoxplotData(realData).boxData; // 实时
    // 保留两位
    aheadData = aheadData.map((x) =>
      x.map((y) => (typeof y === 'number' ? _.round(y, 2).toFixed(2) : y)),
    );
    realData = realData.map((x) =>
      x.map((y) => (typeof y === 'number' ? _.round(y, 2).toFixed(2) : y)),
    );
    aheadData.map((x, i) => {
      for (let dataI = 0; dataI <= 4; dataI++) {
        tableData[dataI][i] = x[dataI];
        tableData[dataI + 5][i] = realData[i][dataI];
      }
    });
    chartSeries[0].data = aheadData;
    chartSeries[1].data = aheadData.map((x) => x[2]); // 中位数
    chartSeries[2].data = realData;
    chartSeries[3].data = realData.map((x) => x[2]); // 中位数
    chartOption.series = chartSeries;
    chartOption.xAxis[0].data = timeList.map((x) => x.title);
  } else {
    let aheadData = (dataSource?.[`dayAhead${pointKey}${keySub}`] || []).map((x) => x?.list || []);
    let realData = (dataSource?.[`realtime${pointKey}${keySub}`] || []).map((x) => x?.list || []);
    aheadData = echarts?.dataTool.prepareBoxplotData(aheadData).boxData; // 日前
    realData = echarts?.dataTool.prepareBoxplotData(realData).boxData; // 实时
    // 保留两位
    aheadData = aheadData.map((x) => x.map((y) => (typeof y === 'number' ? y.toFixed(2) : y)));
    realData = realData.map((x) => x.map((y) => (typeof y === 'number' ? y.toFixed(2) : y)));
    aheadData.map((x, i) => {
      for (let dataI = 0; dataI <= 4; dataI++) {
        tableData[dataI][i] = x[dataI];
        tableData[dataI + 5][i] = realData[i][dataI];
      }
    });
    chartSeries[0].data = aheadData;
    chartSeries[1].data = aheadData.map((x) => x[2]); // 中位数
    chartSeries[2].data = realData;
    chartSeries[3].data = realData.map((x) => x[2]); // 中位数
    chartOption.series = chartSeries;
    chartOption.xAxis[0].data = timeList.map((x) => x.title);
  }

  return {
    tableColumns,
    tableData,
    chartOption,
  };
};

export { fmtDataSource };
